// index.js
const app = getApp();
Page({
  data:{
    text:"",
    messages:[],
    scrollTop:0
  },
  autoScroll() {
    let that = this
    let query = wx.createSelectorQuery()
    // 通过class选择器定位到scorll-view
    query.select('.scroll-text').boundingClientRect(res => {
        that.setData({
            // 由于res.height效果不明显，所以乘以100系数，这个系数可以根据实际效果调整
            scrollTop: res.height * 100
        })
    })
    query.exec(res => {})
  },
  getInputValue(e){
    this.setData({
      text: e.detail.value
    });
  },
  Chat(){
    let that=this;
    let msgs=that.data.messages;
    msgs.push({
      role:"user",
      content:that.data.text
    })
    var task=wx.request({
      url: "https://api.ikeplus.cn/api/Common/Stream",
      method:"get",
      enableChunked:true,
      data:{
        text:that.data.text,
        code:"111"
      },
      success:(res)=>{
        console.log(res)
      }
    })
    let rMsg={
      role:"assistant",
      content:""
    };
    let text="";
    msgs.push(rMsg);
    task.onChunkReceived((res)=>{
      const decoder = new app.encoding.TextDecoder('utf-8');
      text+=decoder.decode(res.data);
      console.log(text)
      rMsg.content = app.towxml(text,'markdown',{
        theme:'dark',					// 主题，默认`light`
        events:{					// 为元素绑定的事件方法
          tap:(e)=>{
            console.log('tap',e);
          }
        }
      });
      that.autoScroll();
      that.setData({
        messages:msgs
      })
    })
  },
  getPhoneNumber(e) {
    // 获取手机号
    wx.request({
      url: "https://localhost:5001/api/Wechat/PhoneLogin",
      method: "Get",
      data: {
        phoneCode: e.detail.code,
      },
      success: (res) => {
        if (res.data.errcode == 0) {
          wx.setStorageSync("phoneNumber", res.data.phone_info.phoneNumber);
          wx.showToast({ title: "登录成功" });
        }
      },
    });
  },
  Login() {
    wx.login({
      success: function (res) {
        if (res.code) {
          // 发起网络请求
          wx.request({
            url: "https://localhost:5001/api/Wechat/Login",
            data: {
              code: res.code,
            },
            success: (res) => {
              if (res.data.errcode == 0) {
                wx.setStorageSync("openId", res.data.openid);
                wx.showToast({ title: "登录成功" });
              }
            },
          });
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      },
    });
  },
});
